﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using Tauren.Business.DLL.Base;
using Tauren.Business.DLL.Resouces;
using Tauren.Business.DLL.RoleInfoDLL;
using Tauren.Business.Entity.Config;
using Tauren.Business.Entity.Const;
using Tauren.Business.Entity.Enum;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Input;
using Tauren.Business.Entity.Model;
using Tauren.Business.Entity.Output;
using Tauren.Business.Infrastructure.Globals;
using Tauren.Business.Service.Base;

namespace Tauren.Business.Service.RoleInfoBLL
{
    internal class RoleInfoService : BaseService, IRoleInfoService
    {
        private IRoleInfoBusiness business;
        public RoleInfoService(IRoleInfoBusiness _business, IConnectionBLLBase connectionBLL, IMenuResourcesBusiness resourcesBusiness) : base(_business, connectionBLL, resourcesBusiness)
        {
            this.business = _business;
            this.ResourcesInfo = GetResources(GlobalConst.RESOURCES_FLAG_MODULE_ROLE_KEY);
            this.JudePrmission(GlobalConst.RESOURCES_FLAG_MODULE_ROLE_KEY.ToLower());
        }

        public IResponseMessage Add(Roleinfo_InPut data)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA));
            bool iscoe = business.IsCodeRepeat(data.AutoId, data.Code);
            if (iscoe) return GlobalErrorType.GLOBAL_REPEAT_CODE.Failure(this.CommonText(GlobalErrorType.GLOBAL_REPEAT_CODE));
            if (data.Res is null || !data.Res.Any()) return GlobalErrorType.GLOBAL_RES_LANGUAGE_REPEAT_ERROR.Failure(this.Resources(GlobalErrorType.GLOBAL_RES_LANGUAGE_REPEAT_ERROR));
            int Msg;
            string lan;
            bool repeat = ValueRepeat(data.Res, out Msg, out lan);
            if (!repeat) return Msg.Failure(string.Format(this.CommonText(Msg), lan));
            double seq = business.GetSeq();
            Roleinfo Model;
            ToModel(data, out Model);
            Model.Enable = true;
            Model.Creatdate = DateTime.Now;
            Model.Creator = Global.EmpId;
            Model.Modifdate = DateTime.Now;
            Model.Modifier = Global.EmpId;
            Model.Sequence = seq;
            using (TransactionScope ts = new TransactionScope())
            {
                bool b = true;
                long id = business.Add(Model);
                if (id > 0)
                {
                    List<RoleRes> Res = new List<RoleRes>();
                    data.Res.ForEach(p =>
                    {
                        Res.Add(new RoleRes() { Language = p.Language, Value = p.Value, RoleId = id });
                    });
                    ///存多语言
                    b = business.Add(Res);
                    ///存权限
                    if (b && data.Permissions != null && data.Permissions.Any())
                    {
                        List<RolePermission> rolePermissions = new List<RolePermission>();
                        data.Permissions.ForEach(p =>
                        {
                            rolePermissions.Add(new RolePermission() { RoleId = id, PermissionId = p.PermissionId });
                        });
                        b = business.Add(rolePermissions, id);
                    }
                    ///存人员
                    if (b && data.PersonInfos != null && data.PersonInfos.Any())
                    {
                        List<RolePersonInfo> personInfos = new List<RolePersonInfo>();
                        data.PersonInfos.ForEach(p =>
                        {
                            personInfos.Add(new RolePersonInfo() { EmpId = p.EmpId, RoleId = id });
                        });
                        b = business.Add(personInfos, id);
                    }
                }
                if (b)
                {
                    ts.Complete();
                    return "".OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_SUCCESSINFO.ToString()));
                }
                else return GlobalErrorType.GLOBAL_SAVE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_FAILURE));
            }
        }

        public IResponseMessage Config(string PageType)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            List<OutPutConfig> Fields = new List<OutPutConfig>();

            OutPutConfig config = new OutPutConfig();
            config.Label = this.CommonText("autoId");
            config.FieldKey = "autoId";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_ROLE_KEY.ToLower();
            config.ControlType = ControlType.number;
            Fields.Add(config);
            config = new OutPutConfig();
            config.Label = this.CommonText("thcode");
            config.FieldKey = "code";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_ROLE_KEY.ToLower();
            config.ControlType = ControlType.text;
            config.Show = true;
            config.Editor = PageType != "view" && PageType != "edit";
            config.Required = PageType != "view" && PageType != "edit";
            Dictionary<object, object> rule = new Dictionary<object, object>();
            if (PageType != "view")
            {
                #region 添加验证规则

                rule.Add("required", true);
                rule.Add("message", this.Resources("rolecoderequired"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///长度
                rule = new Dictionary<object, object>();
                rule.Add("min", 1);
                rule.Add("max", 30);
                rule.Add("message", this.Resources("rolecodemax"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///正则
                rule = new Dictionary<object, object>();
                rule.Add("pattern", "^([a-zA-Z0-9]){1,30}$");
                rule.Add("message", this.Resources("rolecoderegx"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
            }
            Fields.Add(config);
            #endregion
            ///多语言
            config = new OutPutConfig();
            config.FieldKey = "res";
            config.Label = Resources("thvalue");
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_ROLE_KEY.ToLower();
            config.ControlType = ControlType.records;
            config.Show = true;
            config.Editor = PageType != "view";
            //BuliedChildConfig(config.ChildFields, PageType);
            BuliedTableResConfig(config.Tables, PageType);
            Fields.Add(config);

            ///权限
            config = new OutPutConfig();
            config.FieldKey = "permissions";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_ROLE_KEY.ToLower();
            config.ControlType = ControlType.permission;

            config.SelectType = SelectType.multi;
            config.Label = this.CommonText("frpermissions");
            config.Show = true;
            config.Editor = PageType != "view";
            BuliedTableConfig(config.Tables, PageType, new List<FromTableHeader>() { new FromTableHeader { FieldKey = "permissionId", Show = false, Primary = true }, new FromTableHeader { FieldKey = "value" } }, config.Operations);
            Fields.Add(config);

            ///人员
            config = new OutPutConfig();
            config.FieldKey = "personInfos";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_ROLE_KEY.ToLower();
            config.ControlType = ControlType.employee;
            config.Label = this.CommonText("frpersoninfos");
            config.SelectType = SelectType.multi;
            config.Show = true;
            config.Editor = PageType != "view";
            BuliedTableConfig(config.Tables, PageType, new List<FromTableHeader>() { new FromTableHeader { FieldKey = "empId", Show = false }, new FromTableHeader { FieldKey = "cnName" }, new FromTableHeader { FieldKey = "enName" } }, config.Operations);
            Fields.Add(config);
            return Fields.Succeed();
        }

        public IResponseMessage Delete(long AutoID)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            var data = business.FirstDefault(AutoID);
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            data.Enable = false;
            data.HaveDelete = true;
            data.Modifier = Global.EmpId;
            data.Modifdate = DateTime.Now;
            bool b = business.Edit(data);
            if (b) return "".OnSucceed(this.Resources(GlobalErrorType.GLOBAL_DELETE_SUCCESSINFO));
            else return GlobalErrorType.GLOBAL_DELETE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_DELETE_FAILURE));
        }

        public IResponseMessage Edit(Roleinfo_InPut data)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA));
            Roleinfo single = business.FirstDefault(data.AutoId);
            if (single is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            bool iscoe = business.IsCodeRepeat(data.AutoId, data.Code);
            if (iscoe) return GlobalErrorType.GLOBAL_REPEAT_CODE.Failure(this.CommonText(GlobalErrorType.GLOBAL_REPEAT_CODE));
            if (data.Res is null || !data.Res.Any()) return GlobalErrorType.GLOBAL_RES_LANGUAGE_REPEAT_ERROR.Failure(this.Resources(GlobalErrorType.GLOBAL_RES_LANGUAGE_REPEAT_ERROR));
            int Msg;
            string lan;
            bool repeat = ValueRepeat(data.Res, out Msg, out lan);
            if (!repeat) return Msg.Failure(string.Format(this.CommonText(Msg), lan));
            single.HaveSystemRole = data.HaveSystemRole;
            single.Modifdate = DateTime.Now;
            single.Modifier = Global.EmpId;
            using (TransactionScope ts = new TransactionScope())
            {
                bool b = business.Edit(single);
                if (b)
                {
                    List<RoleRes> Res = new List<RoleRes>();
                    data.Res.ForEach(p =>
                    {
                        Res.Add(new RoleRes() { Language = p.Language, Value = p.Value, RoleId = single.AutoId });
                    });
                    ///存多语言
                    b = business.Add(Res);
                    ///存权限
                    if (b)
                    {
                        List<RolePermission> rolePermissions = new List<RolePermission>();
                        if (data.Permissions != null && data.Permissions.Any())
                            data.Permissions.ForEach(p =>
                            {
                                rolePermissions.Add(new RolePermission() { RoleId = single.AutoId, PermissionId = p.PermissionId });
                            });
                        b = business.Add(rolePermissions, single.AutoId);
                    }
                    ///存人员
                    if (b)
                    {
                        List<RolePersonInfo> personInfos = new List<RolePersonInfo>();
                        if (data.PersonInfos != null && data.PersonInfos.Any())
                            data.PersonInfos.ForEach(p =>
                            {
                                personInfos.Add(new RolePersonInfo() { EmpId = p.EmpId, RoleId = single.AutoId });
                            });
                        b = business.Add(personInfos, single.AutoId);
                    }
                }
                if (b)
                {
                    ts.Complete();
                    return "".OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_SUCCESSINFO.ToString()));
                }
                else return GlobalErrorType.GLOBAL_SAVE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_FAILURE));
            }
        }

        public IResponseMessage Enable(long AutoID)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            var data = business.FirstDefault(AutoID);
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            data.Enable = !data.Enable;
            data.Modifier = Global.EmpId;
            data.Modifdate = DateTime.Now;
            bool b = business.Edit(data);
            if (b) return "".OnSucceed(this.CommonText(data.Enable ? GlobalErrorType.GLOBAL_ENABLE_SUCCESSINFO : GlobalErrorType.GLOBAL_DISABLE_SUCCESSINFO));
            else return data.Enable ? GlobalErrorType.GLOBAL_ENABLE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_ENABLE_FAILURE)) : GlobalErrorType.GLOBAL_DISABLE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_DISABLE_FAILURE));
        }

        public IResponseMessage Get(long AutoID)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            List<RoleInfoTable> tables = business.Get(AutoID);
            Roleinfo_OutPut _OutPut = new Roleinfo_OutPut();
            if (tables is null || !tables.Any())
            {
                _OutPut.Res = new List<RoleRes_OutPut>() { new RoleRes_OutPut() { Language = "", Value = "" } };
            }
            else
            {
                RoleInfoTable table = tables.FirstOrDefault();
                ///隐射数据
                ToViewModel(table, out _OutPut);
                if (!(_OutPut is null))
                {
                    ///装多语言
                    tables.GroupBy(o => new { o.Code, o.AutoId }).ToList().ForEach(p =>
                    {
                        p.ToList().ForEach(c =>
                        {
                            _OutPut.Res.Add(new RoleRes_OutPut() { RoleId = c.AutoId, Language = c.Language, Value = c.Value });
                        });
                    });
                    ///装权限
                    var Permissions = business.GetRolePermissions(AutoID);
                    if (Permissions.Any())
                    {
                        _OutPut.Permissions = Permissions;
                    }
                    ///装具有该角色的人员
                    var PersonInfos = business.GetRolePersonInfos(AutoID);
                    if (PersonInfos.Any())
                    {
                        _OutPut.PersonInfos = PersonInfos;
                    }
                }
            }
            return _OutPut.Succeed();
        }

        public IResponseMessage Pages(QueryModel queryModel)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            TableListModel<PageRoleInfoTable> tableListModel = new TableListModel<PageRoleInfoTable>();
            List<TableListHeaderModele> Headers = new List<TableListHeaderModele>();
            Headers.Add(new TableListHeaderModele() { Key = "rowNo", Name = CommonText("rowNo"), Width = 50, Align = "center", Fixed = true });
            Headers.Add(new TableListHeaderModele() { Key = "autoId", Name = CommonText("autoId"), Width = 70, Hide = true, Type = "primary_key", Align = "center", SorTable = SortType.custom.ToString() });
            Headers.Add(new TableListHeaderModele() { Key = "code", Name = CommonText("thcode"), Width = 200, Type = "primary_name", Align = "center", SorTable = SortType.custom.ToString(), IsOperation = true, Fixed = true, Filter = true });

            Headers.Add(new TableListHeaderModele() { Key = "value", Name = Resources("thvalue"), Width = 240, Filter = true, Fixed = true });
            Headers.Add(new TableListHeaderModele() { Key = "language", Name = CommonText("languageType"), Width = 120, Align = "center", SorTable = SortType.custom.ToString() });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Enable", Name = CommonText("thstate"), Width = 80, IsTag = true, Align = "center", SorTable = SortType.custom.ToString() });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Creator", Name = CommonText("diccreator"), Width = 120, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Creatdate", Name = CommonText("diccreatdate"), Width = 160, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "action", Name = "操作", Width = 160, Align = "center" });
            List<AccountListModel> employeeListModels = new List<AccountListModel>();
            long Total = 0;
            List<PageRoleInfoTable> Data = business.Pages(queryModel, out Total);
            if (Data.Any())
            {
                Data.ForEach(o =>
                {
                    o.Dic_Enable = CommonText(o.Enable ? GlobalConst.RESOURCES_CONTENT_ENABLE_KEY : GlobalConst.RESOURCES_CONTENT_DISABLE_KEY);
                    o.Language = Languages(GlobalConst.LANGUAGE_CONTENT_LANGUAGE_KEY);
                    o.Dic_Creator = EmpDictionary.ContainsKey(o.Creator) ? EmpDictionary[o.Creator] : "";
                    o.Dic_Modifier = EmpDictionary.ContainsKey(o.Modifier) ? EmpDictionary[o.Modifier] : "";
                    o.Row_Style = o.Enable ? "" : "danger";
                    o.Dic_Creatdate = o.Creatdate.Value.ToString(GlobalConst.DATE_FORMAT_SECONDS);
                    o.Operations = new List<SystemButton>();
                    if (Global.IsAdmin && (Buttons is null || !Buttons.Any()))
                    {
                        BuliderButtons(o.Operations, o.Code, o.AutoId, ButtomType.edit);
                        BuliderButtons(o.Operations, o.Code, o.AutoId, ButtomType.detaile);
                        BuliderButtons(o.Operations, o.Code, o.AutoId, !o.Enable ? ButtomType.enable : ButtomType.disable);
                        BuliderButtons(o.Operations, o.Code, o.AutoId, ButtomType.delete);
                    }
                    else
                    {
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.detaile.ToString()))
                            BuliderButtons(o.Operations, o.Code, o.AutoId, ButtomType.edit);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.edit.ToString()))
                            BuliderButtons(o.Operations, o.Code, o.AutoId, ButtomType.detaile);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && (o.Value == ButtomType.enable.ToString() || o.Value == ButtomType.disable.ToString())))
                            BuliderButtons(o.Operations, o.Code, o.AutoId, !o.Enable ? ButtomType.enable : ButtomType.disable);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.delete.ToString()))
                            BuliderButtons(o.Operations, o.Code, o.AutoId, ButtomType.delete);
                    }
                });
            }
            tableListModel.Body = Data;
            tableListModel.Total = Total;
            tableListModel.Header = Headers;
            if (Global.IsAdmin && (Buttons is null || !Buttons.Any()))
            {
                BuliderButtons(tableListModel.Operations, "", 0, ButtomType.add);
            }
            else
            {
                if (Buttons.Any(o => o.Value == ButtomType.add.ToString()))
                    BuliderButtons(tableListModel.Operations, "", 0, ButtomType.add);
            }
            return tableListModel.Succeed();
        }

        public IResponseMessage Template(string key)
        {
            switch (key)
            {
                case "res": return new RoleRes_OutPut() { Language = "", Value = "" }.OnSucceed();
                case "permissions": return new RolePermission_OutPut() { PermissionId = 0, Value = "" }.OnSucceed();
                default: return new RolePersonInfo_OutPut() { EmpId = 0, CNName = "", ENName = "" }.OnSucceed();
            }
        }

        #region private
        private bool ValueRepeat(List<Entity.Input.RoleRes_InPut> ChildFieldValues, out int Msg, out string lan)
        {
            bool b = true;
            Msg = 0;
            lan = "";
            var groups = ChildFieldValues.GroupBy(o => o.Language).Select(n => new { Language = n.Key, cout = n.Count() });
            foreach (var item in groups)
            {
                if (item.cout > 1)
                {
                    b = false;
                    Msg = GlobalErrorType.GLOBAL_LANGUAGE_REPEAT_ERROR;
                    lan = item.Language;
                    break;
                }
            }
            return b;
        }
        protected override void BuliedTableResConfig(List<TableListHeaderModele> Headers, string pageType)
        {
            Dictionary<object, object> rule = new Dictionary<object, object>();
            rule.Add("required", true);
            rule.Add("message", this.Resources("resnamerequired"));
            rule.Add("trigger", "change");
            Headers.Add(new TableListHeaderModele()
            {
                Key = "language",
                Name = CommonText("languageType"),
                Align = "left",
                Options = this.Options,
                Rules = pageType != "view" ? new List<Dictionary<object, object>>() { rule } : new List<Dictionary<object, object>>(),
                Show = true,
                Editor = pageType != "view",
                ControlType = ControlType.parameter,
            });
            ///长度
            rule = new Dictionary<object, object>();
            rule.Add("min", 0);
            rule.Add("max", 200);
            rule.Add("message", this.Resources("resvaluelength"));
            rule.Add("trigger", "blur");
            Headers.Add(new TableListHeaderModele()
            {
                Key = "value",
                Name = Resources("thvalue"),
                IsOperation = true,
                Align = "center",
                Rules = pageType != "view" ? new List<Dictionary<object, object>>() { rule } : new List<Dictionary<object, object>>(),
                Show = true,
                Editor = pageType != "view",
                ControlType = ControlType.textarea
            });
        }
        #endregion
    }
}
